package top.xcxdl.rural.controller.admin;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import top.xcxdl.rural.common.Res;
import top.xcxdl.rural.entity.RuralProduct;
import top.xcxdl.rural.entity.RuralQuestion;
import top.xcxdl.rural.service.IRuralQuestionService;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Ding
 * @since 2022-05-06
 */
@RestController
@RequestMapping("/admin/question")
public class BackRuralQuestionController {

    @Resource
    private IRuralQuestionService service;

    @GetMapping("/getList")
    @ApiOperation("获取题库列表")
    @ResponseBody
    public Res<Object> getList(
            @RequestParam(name = "page_no") Integer pageNo,
            @RequestParam(name = "page_size") Integer pageSize,
            @RequestParam(name = "question_type", required = false) Integer questionType,
            @RequestParam(name = "title", required = false) String key
    ) {
        PageInfo<RuralQuestion> pageInfo = service.getList(pageNo, pageSize, questionType, key);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return Res.success(jsonObject);
    }

    @GetMapping("/getDetail")
    @ApiOperation("获取题库详情")
    @ResponseBody
    public Res<Object> getList(
            @RequestParam(name = "question_id") Integer questionId
    ) {
        RuralQuestion question = service.getDetailById(questionId);
        return Res.success(question);
    }

    @PostMapping("/doEdit")
    @ApiOperation("添加 / 编辑题库")
    @ResponseBody
    public Res<Object> doEdit(@RequestBody RuralQuestion question) {
        //转换为String
        question.setQuestionOptions(JSONArray.toJSONString(question.getQuestionOptionsBody()));
        question.setQuestionCorrect(JSONArray.toJSONString(question.getQuestionCorrectBody()));
        int ret = 0;
        boolean isNew = question.getQuestionId() == null;
        ret += service.doEdit(question);
        return ret > 0 ? Res.success(isNew ? "录入成功" : "编辑成功") : Res.error("操作失败");
    }

    @PostMapping("/doDelete")
    @ApiOperation("删除题库")
    @ResponseBody
    public Res<Object> doDelete(@RequestBody JSONObject jsonObject) {
        //获取id集合
        List<Integer> ids = (List<Integer>) jsonObject.get("ids");
        //删除
        int ret = service.doDelete(ids);
        return ret > 0 ? Res.success("删除成功") : Res.error("删除失败");
    }
}
